<template>
  <div class="base-tree-box">
    <el-tree :data="data" draggable :highlight-current='true' :props="defaultProps" @node-click="handleNodeClick"
      :default-expand-all="true" @node-drop="handleDrop">
      <template #default="{ node, data }">
        <span>
          <span>
            <el-icon v-if="!node.expanded">
              <i class="dtreefont dtree-icon-jia dtree-theme-dtreefont dtree-theme-ficon" data-spread="close"
                data-id="53" dtree-id="deviceTree" data-iconclass=""></i>
            </el-icon>
            <el-icon v-if="node.expanded">
              <i v-if='node.level != 3' class="dtree-theme-dtreefont dtree-theme-ficon dtreefont dtree-icon-jian"
                data-spread="open" data-id="53" dtree-id="deviceTree" data-iconclass=""></i>
            </el-icon>
            <el-icon v-if="data.children.length == 0">
              <i v-if='node.level != 3' class="dtree-theme-dtreefont dtree-theme-ficon dtreefont dtree-icon-jian"
                :class="data.iconClass" data-spread="last" dtree-id="deviceTree" data-iconclass=""></i>
              <i v-if='node.level == 3' class="dtreefont dtree-icon-shuye1 dtree-theme-dtreefont dtree-theme-ficon"
                data-spread="open" data-id="53" dtree-id="deviceTree" data-iconclass=""></i>
            </el-icon>
            {{ node.label }}
          </span>
        </span>
      </template>
    </el-tree>

  </div>
</template>

<script setup>
let emit = defineEmits(['query'])
let data = ref([])

const formatToTree = (ary, pid, pidName = 'parentId') => {
  return ary
    .filter((item) => item[pidName] === pid)
    .map((item) => {
      // 通过父节点ID查询所有子节点
      item.children = formatToTree(ary, item.id);
      return item;
    });
}

const getList = () => { // 获取表格数据
  data.loading = true;
  $axios.post('/sel/loadMenuMangerLeftTreeJson', {
  }).then(res => {
    data.value = formatToTree(res.data.data, 0)
  })
  data.loading = false;
}

const handleNodeClick = (data) => {
  let id = data.id;
  emit('query', { id: id })
}

const defaultProps = {
  children: 'children',
  label: 'title',
}

const handleDrop = (
  draggingNode,
  dropNode,
  dropType,
  ev
) => {
  let num = 0;
  let list = data.value[0];
  for (let i = 0; i < list.children.length; i++) {
    list.children[i].menuId = i + 1;
    for (let j = 0; j < list.children[i].children.length; j++) {
      num++
      list.children[i].children[j].menuId = num;
    }
  }
  $axios.post('/sel/moveMenu', list.children).then(res => { })
}
onBeforeMount(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.base-tree-box {
  padding-left: 1rem;
  height: 100%;
  overflow: overlay;
  background-color: #212121;
}

:deep(.el-tree-node__expand-icon.expanded) {
  display: none;
}

:deep(.el-tree-node__expand-icon) {
  display: none;
}

:deep(.el-icon:empty) {
  display: none;
}
</style>